<?php
@session_start();

class nfwk_schema extends nfwk {

    private $_modelid     = null;
    private $_modelname   = null;
    private $_modelfields = array();
    public $_sqlschema   = null;
    public $_formschema  = null;
    
    //--------------------------------------------------------------------------
    
    /*
     * SELECT b.* FROM nfwk_models AS a, nfwk_schemas AS b WHERE a.name='post' and a.id=b.model_id
     * SELECT b.model_id FROM nfwk_models AS a, nfwk_schemas AS b WHERE a.name='post' and a.id=b.model_id GROUP BY b.model_id
     */
    
    public function build_schema_from_model($model) {
        
        nfwk::open_db();
        $model = $this->_DBCONN->GetRow("SELECT id, name FROM nfwk_models WHERE name='".strtolower($model)."'");
        
        if ($model['id'] == '' || empty($model['id'])) {
            die("<pre><b>ERRORE: </b>Impossibile determinare un modello valido per <b>$model</b></pre>");

        } else {
            
            // Assegno le variabili private necessarie alla classe
            $this->_modelid     = $model['id'];
            $this->_modelname   = $model['name'];
            $this->_modelfields = $this->_DBCONN->GetArray("select * from nfwk_schemas where model_id = ".$this->_modelid);
            
            /*
             * le due chiamate sotto non sono necessarie in quanto le informazioni
             * vengono recuperate se alla funzione build_schema_from_model viene
             * passato un nome di modello valido.
             *
             * nfwk_schema::get_model_id();
             * nfwk_schema::get_model_fields();
             */
            nfwk_schema::generate_sql_schema();
            nfwk_schema::generate_form_schema();
            nfwk_schema::create_default_controllers();
            //nfwk_schema::create_table_from_sql();
        }
        
        return 0;
    }
    //--------------------------------------------------------------------------


    private function get_model_id() {
        
        nfwk::open_db();
        $this->_modelid = $this->_DBCONN->GetOne("SELECT id FROM nfwk_models WHERE name = '".$this->_modelname."'");
        
        return 0;
    }
    //--------------------------------------------------------------------------
    
    private function get_model_fields() {
        
        nfwk::open_db();
        $this->_modelfields = $this->_DBCONN->GetArray("select * from nfwk_schemas where model_id = ".$this->_modelid);

        return 0;

    }
    //--------------------------------------------------------------------------


    private function generate_sql_schema() {

        $this->_sqlschema = "CREATE TABLE IF NOT EXISTS `".$this->_modelname."` ( ";
        
        foreach($this->_modelfields as $row) {

            if ($row['autoinc'] == "1") {
                $PRIMARY_KEY = "PRIMARY KEY (`".$row['name']."`)";
            }
            
            $param = array('name'          => $row['name'],
                           'type'          => $row['type'],
                           'autoinc'       => $row['autoinc'],
                           'lenght'        => $row['lenght'],
                           'def_value'     => $row['default_value'] );

            $this->_sqlschema .= nfwk_core::build_field($param, 'sql').", ";

        }

        $this->_sqlschema .= $PRIMARY_KEY." )";

        $this->_sqlschema = nfwk_core::string_finishing('sql_schema', $this->_sqlschema);
        
        

        nfwk_schema::update_nfwk_schemas('SQL', $this->_sqlschema);
        
        return 0;
    }
    //--------------------------------------------------------------------------

    
    private function generate_form_schema($action="#", $method='post', $buttons='both') {
        
        // Template dei bottoni di reset ed invio
        $button_submit = "<input type='submit' value='invia' />";
        $button_clear  = "<input type='reset' value='cancel' />";
        
        if (strtolower($buttons) == "both") {
            $buttons_content = $button_submit."&nbsp;".$button_clear;
        } elseif (strtolower($buttons) == "clear") {
            $buttons_content = $button_clear;
        } elseif (strtolower($buttons) == "submit") {
            $buttons_content = $button_submit;
        } else {
            $buttons_content = $button_submit."&nbsp;".$button_clear;
        }

        $this->_formschema = "<form name='form_".$this->_modelname."' action='".$action."' method='".$method."'>\n";
        
        foreach($this->_modelfields as $row) {
            
            if ($row['visible'] != 0) {
            
                $param = array('name'      => $row['name'],
                               'type'      => $row['type'],
                               'lenght'    => $row['lenght'],
                               'label'     => $row['label'],
                               'visible'   => $row['visible'],
                               'def_value' => $row['default_value'],
                               'model'     => $this->_modelname);

                $this->_formschema .= "<div><label for='".$this->_modelname."_".$row['name']."'>".$row['label']."</label>";
                $this->_formschema .= nfwk_core::build_field($param, 'form')."</div>\n";
            }

        }

        $this->_formschema .= $buttons_content."\n";
        $this->_formschema .= "</form>\n";

        $this->_formschema = trim($this->_formschema);


        nfwk_schema::update_nfwk_schemas('FORM', $this->_formschema);
        
        return 0;
    }
    //--------------------------------------------------------------------------


    private function create_default_controllers() {
        
        $field_list      = "";
        $value_list      = "";
        $where_condition = "";
        $update_list     = "";
 
        
        foreach($this->_modelfields as $row) {
            
            if ($row['autoinc'] == "0") {
                
                $insert_field_list .= $row['name']." ";
                
                if ($row['type'] == "INT" || $row['type'] == "FLOAT") {
                    $value_list  .= "%".$this->_modelname."_".$row['name']."% ";
                    $update_list .= $row['name']."=%".$this->_modelname."_".$row['name']."% ";
                    
                } else {
                    $value_list  .= "'%".$this->_modelname."_".$row['name']."%' ";
                    $update_list .= $row['name']."='%".$this->_modelname."_".$row['name']."%' ";
                    
                }
            } else {
                if ($row['type'] == "INT" || $row['type'] == "FLOAT") {
                    $where_condition = $row['name']." = %".$this->_modelname."_".$row['name']."% ";
                    
                } else {
                    $where_condition = $row['name']." = '%".$this->_modelname."_".$row['name']."%' ";
                    
                }
            }
        }

        
        // Sistemazione dei campi e dei valori per azione: INSERT
        $insert_field_list = trim($insert_field_list);
        $insert_value_list = trim($insert_value_list);
        $update_list = trim($update_list);
        $insert_field_list = str_replace(" ", ", ", $insert_field_list);
        $insert_value_list = str_replace(" ", ", ", $insert_value_list);
        $update_list = str_replace(" ", ", ", $update_list);

        // Generazione stringhe per controllers predefiniti
        $controller['insert'] = "INSERT INTO ".$this->_modelname. " (".$insert_field_list.") VALUE (".$value_list.")";
        $controller['delete'] = "DELETE FROM ".$this->_modelname." WHERE ".$where_condition;
        $controller['update'] = "UPDATE ".$this->_modelname." SET ".$update_list." WHERE ".$where_condition;

        
        
        
        foreach ($controller as $key=>$value) {

            nfwk::open_db();
            $controller_exist = $this->_DBCONN->GetRow("SELECT * FROM nfwk_controllers WHERE model_id = ".$this->_modelid." AND type = '".strtoupper($key)."' AND value = '".addslashes($value)."'");

            if ($controller_exist['id'] > 0) {
                if ($controller_exist['value'] != addslashes($value)) {
                    
                    $this->_DBCONN->Execute("UPDATE nfwk_controllers SET value = '".addslashes($value)."' WHERE id = ".$controller_exist['id']);
                }
            } else {
                $this->_DBCONN->Execute("INSERT INTO nfwk_controllers (model_id, type, value) VALUE (".$this->_modelid.", '".strtoupper($key)."', '".addslashes($value)."')");
            }
        
            $this->_DBCONN->Execute($this->_sqlschema);

        }


        return 0;

    }
    //--------------------------------------------------------------------------
    

    private function create_table_from_sql() {
        
        nfwk::open_db();
        $this->_DBCONN->Execute($this->_sqlschema);
        
        return 0;
    }
    //--------------------------------------------------------------------------

    
    private function update_nfwk_schemas($type, $value) {
        
        nfwk::open_db();
        
        if (strtoupper($type) == "SQL" || strtoupper($type) == "FORM") {
            $type = strtoupper($type);
        } else {
            die("<b>Errore:</b> Non posso proedere se non viene specificato un type corretto (FROM o SQL)");
        }
        
        $SchemaExists = $this->_DBCONN->GetRow("SELECT id, content FROM nfwk_compiled_schemas WHERE content = '".addslashes($value)."' ORDER BY id DESC");
        if ($SchemaExists['id'] > 0) {
            if ($SchemaExists['content'] != addslashes($value)) {
                $this->_DBCONN->Execute("UPDATE nfwk_compiled_schemas SET content = '".addslashes($value)."' WHERE id = ".$SchemaExists['id']);
            }
        } else {
            $this->_DBCONN->Execute("INSERT INTO nfwk_compiled_schemas (model_id, type, content) VALUE (".$this->_modelid.", '".strtoupper($type)."', '".addslashes($value)."')");
        }

    }
    //--------------------------------------------------------------------------

    
    function debug() {
        echo "<pre>";
        echo "Model ID.....: ".$this->_modelid."<br>";
        echo "Model Name...: ".$this->_modelname."<br><hr><br>";
        echo "SQL Schema...:<br><br>";
        echo htmlentities($this->_sqlschema)."<br><hr><br>";
        echo "FORM Schema..:<br><br>";
        echo htmlentities($this->_formschema)."<br><hr><br>";
        echo "Model Fields:<br>";
        
        foreach ($this->_modelfields as $row) {
            print_r($row);
        }
        
        echo "<hr></pre>";
    }
    
}

?>
